package com.sxz.sbs.module.amortize;

import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.app.GlideApp;
import com.sxz.sbs.applibrary.KeyBordStateUtil;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.amortize.adapter.AmortizeAdapter;
import com.sxz.sbs.module.amortize.presenter.AmortizeCalculatorPresenter;
import com.sxz.sbs.module.amortize.presenter.AmortizeCalculatorView;
import com.sxz.sbs.module.client.bean.AllHousesBean;
import com.sxz.sbs.router.RouterUrl;
import com.sxz.sbs.widget.CommonTitle;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 分期计算器
 */
@Route(path = "/login/calculator")
public class AmortizeCalculatorActivity extends BaseActivity<AmortizeCalculatorPresenter>
        implements AmortizeCalculatorView {

    @BindView(R.id.tv_amortize_house)
    TextView tvAmortizeHouse;
    @BindView(R.id.tv_amortize_price)
    ClearEditText cetAmortizePrice;
    @BindView(R.id.cet_amortize_payment)
    ClearEditText cetAmortizePayment;
    @BindView(R.id.iv_amortize_bank)
    ImageView ivAmortizeBank;
    @BindView(R.id.tv_amortize_bank_name)
    TextView tvAmortizeBankName;
    @BindView(R.id.rv_amortize)
    RecyclerView rvAmortize;
    @BindView(R.id.tv_amortize_total_price)
    TextView tvAmortizeTotalPrice;
    @BindView(R.id.tv_amortize_month_price)
    TextView tvAmortizeMonthPrice;
    @BindView(R.id.tv_amortize_first_price)
    TextView tvAmortizeFirstPrice;
    @BindView(R.id.tv_amortize_loan_price)
    TextView tvAmortizeLoanPrice;
    @BindView(R.id.tv_amortize_interest_price)
    TextView tvAmortizeInterestPrice;
    @BindView(R.id.tv_amortize_bank_rate)
    TextView tvAmortizeBankRate;
    private AmortizeAdapter adapter;
    private List<AmortizeBankBean.DataListBean> dataList = new ArrayList<>();
    private int selectParkingId;
    private List<AmortizeBankBean> bankList = new ArrayList<>();
    private KeyBordStateUtil keyBordStateUtil;
    private int totalValue, firstValue;
    private AmortizeBankBean.DataListBean amortizeBean;
    private DecimalFormat df = new DecimalFormat("######0.000");
    private DecimalFormat dfMonth = new DecimalFormat("######0.00");

    @Override
    protected void init() {
        new CommonTitle.Builder(this).setTitle("分期计算器").build().show();
        rvAmortize.setLayoutManager(new GridLayoutManager(this, 3));
        adapter = new AmortizeAdapter(dataList);
        keyBordStateUtil = new KeyBordStateUtil(this);
        keyBordStateUtil.addOnKeyBordStateListener(mOnKeyBordStateListener);
        getParking();
        rvAmortize.setAdapter(adapter);
        rvAmortize.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter1, View view, int position) {
                adapter.setSelectPosition(position);
                amortizeBean = dataList.get(position);
                tvAmortizeBankRate.setText("月利率" + df.format
                        (dataList.get(position).getInterestRate() / dataList.get(position).getNumBers()) + "%");
            }
        });
    }

    private void getParking() {
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("keyWords", "");
        map.put("pageNumber", 1);
        map.put("pageSize", AppConstant.PAGE_SIZE);
        mPresenter.getAllHouses(map, false);
    }

    private KeyBordStateUtil.onKeyBordStateListener mOnKeyBordStateListener = new KeyBordStateUtil.onKeyBordStateListener() {
        @Override
        public void onSoftKeyBoardShow(int keyboardHeight) {

        }

        @Override
        public void onSoftKeyBoardHide() {
           /* if (!TextUtils.isEmpty(cetAmortizePrice.getInputValue())) {
                int sf = Integer.parseInt(cetAmortizePrice.getInputValue()) +500;
                int shang = sf/1000;
                int value = shang*1000;
                totalValue = value;
                cetAmortizePrice.setText(value+"");
                cetAmortizePrice.setSelection(cetAmortizePrice.getInputValue().length());
            } else {
                totalValue = 0;
            }
            if (!TextUtils.isEmpty(cetAmortizePayment.getInputValue())) {
                int sf = Integer.parseInt(cetAmortizePayment.getInputValue()) +500;
                int shang = sf/1000;
                int value = shang*1000;
                firstValue = value;
                cetAmortizePayment.setText(value+"");
                cetAmortizePayment.setSelection(cetAmortizePayment.getInputValue().length());
            } else {
                firstValue = 0;
            }
*/
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_amortize_calculator;
    }

    @Override
    protected AmortizeCalculatorPresenter createPresenter() {
        return new AmortizeCalculatorPresenter();
    }

    @OnClick({R.id.ll_amortize_house, R.id.rl_amortize_bank, R.id.btn_calculate})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_amortize_house:
                ARouter.getInstance().build(RouterUrl.STAFF_HANDLE)
                        .withString("status", "status=amortize")
                        .navigation(this, 1009);
                break;
            case R.id.rl_amortize_bank:
                if (bankList.size() > 0) {
                    startActivityForResult(new Intent(this, SelectBankActivity.class)
                                    .putParcelableArrayListExtra("bank", (ArrayList<? extends Parcelable>) bankList)
                            , 1010);
                } else {
                    ToastUtils.showShort("没有分期银行");
                }
                break;
            case R.id.btn_calculate:
                if (TextUtils.isEmpty(tvAmortizeHouse.getText().toString())) {
                    ToastUtils.showShort("请选择小区");
                    return;
                }

                if (TextUtils.isEmpty(cetAmortizePrice.getInputValue())) {
                    ToastUtils.showShort("请输入车位价格");
                    return;
                }
                jiSuan();
                if (firstValue > totalValue) {
                    ToastUtils.showShort("首付价格不能大于总价");
                    return;
                }
                if (dataList.size() <= 0) {
                    ToastUtils.showShort("请选择银行");
                    return;
                }

                tvAmortizeTotalPrice.setText(totalValue + "元");
                tvAmortizeFirstPrice.setText(firstValue + "元");
                tvAmortizeLoanPrice.setText((totalValue - firstValue) + "元");
                if (amortizeBean != null) {
                    double yearRate = 0;
                    if (amortizeBean.getYearOrMonth() == 1) {
                        yearRate = amortizeBean.getInterestRate() / 100 * amortizeBean.getNumBers();
                    } else if (amortizeBean.getYearOrMonth() == 2) {
                        yearRate = amortizeBean.getInterestRate() / 100;
                    }
                    double monthPrice = ((totalValue - firstValue) + ((totalValue - firstValue) * yearRate)) / amortizeBean.getNumBers();
                    tvAmortizeMonthPrice.setText(dfMonth.format(monthPrice) + "元(" + (amortizeBean.getNumBers() / 12) + "年)");
                    double interestPrice = 0;
                    if (amortizeBean.getYearOrMonth() == 1) {
                        interestPrice = (totalValue - firstValue)
                                * (amortizeBean.getInterestRate() / 100) * amortizeBean.getNumBers();
                    } else if (amortizeBean.getYearOrMonth() == 2) {
                        interestPrice = (totalValue - firstValue) * (amortizeBean.getInterestRate() / 100);
                    }
                    tvAmortizeInterestPrice.setText(dfMonth.format(interestPrice) + "元");
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        switch (requestCode) {
            case 1009:
                selectParkingId = data.getIntExtra("parkId", 0);
                tvAmortizeHouse.setText(data.getStringExtra("parkName"));
                getBank(selectParkingId);
                break;
            case 1010:
                AmortizeBankBean amortizeBankBean = data.getParcelableExtra("bank_result");
                dataList.clear();
                dataList.addAll(amortizeBankBean.getDataList());
                adapter.setFirst(true);
                adapter.selectPosition(-1);
                adapter.notifyDataSetChanged();
                amortizeBean = amortizeBankBean.getDataList().get(0);
                GlideApp.with(this).load(amortizeBankBean.getPhotoUrl()).circleCrop().into(ivAmortizeBank);
                tvAmortizeBankName.setText(amortizeBankBean.getBankName());
                tvAmortizeBankRate.setText("月利率" + df.format
                        (amortizeBankBean.getDataList().get(0).getInterestRate() / amortizeBankBean.getDataList().get(0).getNumBers()) + "%");
                break;
            default:
                break;
        }
    }

    @Override
    public void onGetHousesDataSuccess(AllHousesBean bean) {
        if (mIsLive && bean.getList() != null && bean.getList().size() > 0) {
            selectParkingId = bean.getList().get(0).getId();
            tvAmortizeHouse.setText(bean.getList().get(0).getName());
            getBank(selectParkingId);
        }
    }

    @Override
    public void onGetBankDataSuccess(List<AmortizeBankBean> data) {
        if (mIsLive && data != null && data.size() > 0) {
            bankList.clear();
            bankList.addAll(data);
            dataList.clear();
            dataList.addAll(data.get(0).getDataList());
            adapter.notifyDataSetChanged();
            amortizeBean = data.get(0).getDataList().get(0);
            GlideApp.with(this).load(data.get(0).getPhotoUrl()).circleCrop().into(ivAmortizeBank);
            tvAmortizeBankName.setText(data.get(0).getBankName());
            tvAmortizeBankRate.setText("月利率" + df.format
                    (data.get(0).getDataList().get(0).getInterestRate() / data.get(0).getDataList().get(0).getNumBers()) + "%");
        }
    }

    private void getBank(int selectParkingId) {
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("parkingId", selectParkingId);
        mPresenter.getBank(map);
    }

    @Override
    protected void onDestroy() {
        if (keyBordStateUtil != null) {
            keyBordStateUtil.removeOnKeyBordStateListener();
        }
        super.onDestroy();

    }

    private void jiSuan() {
        if (!TextUtils.isEmpty(cetAmortizePrice.getInputValue())) {
            int sf = Integer.parseInt(cetAmortizePrice.getInputValue()) + 500;
            int shang = sf / 1000;
            int value = shang * 1000;
            totalValue = value;
            cetAmortizePrice.setText(value + "");
            cetAmortizePrice.setSelection(cetAmortizePrice.getInputValue().length());
        } else {
            totalValue = 0;
        }
        if (!TextUtils.isEmpty(cetAmortizePayment.getInputValue())) {
            int sf = Integer.parseInt(cetAmortizePayment.getInputValue()) + 500;
            int shang = sf / 1000;
            int value = shang * 1000;
            firstValue = value;
            cetAmortizePayment.setText(value + "");
            cetAmortizePayment.setSelection(cetAmortizePayment.getInputValue().length());
        } else {
            firstValue = 0;
        }
    }
}
